package com.yinxianren.main.study.netty.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TimeClient {

    private int port=8080;
    private Socket socket=null;
    private BufferedReader bufferedReader=null;
    private PrintWriter printWriter=null;

    public static void main(String[] args) {
        for(int i=0;i<1000;i++){
            new Thread(()->{
                TimeClient tc= new TimeClient();
                tc.client(args);
            }).start();
        }
    }

    /**
     *
     * @param args
     */
    private void client(String[] args){

        try{
            if(null != args && args.length>0){
                port=Integer.valueOf(args[0]);
            }
            socket=new Socket("127.0.0.1",port);
            bufferedReader=new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            printWriter=new PrintWriter(this.socket.getOutputStream(),true);
            printWriter.println("QUERY THE ORDER");
            System.out.println("【client】 Send order two server success");
            String resp=bufferedReader.readLine();
            System.out.println("【client】 receive message : "+ resp);
            printWriter.println(resp);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeResource(bufferedReader,socket,printWriter);
        }

    }


    private boolean closeResource(BufferedReader bufferedReader,Socket socket,PrintWriter printWriter){
        if(null != bufferedReader){
            try{
                bufferedReader.close();
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }

        if(null != printWriter){
            printWriter.close();
        }

        if(null != socket){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        System.out.println("【client】 close resource!");
        return true;
    }

}
